import 'dart:io';

import 'dart:typed_data';
import 'dart:ui' as ui;

import 'package:kmxy_base/base/base_package.dart';

class ImageUtil {
  static final ImageUtil getInstance = ImageUtil._internal();

  ///工厂构造函数
  factory ImageUtil() => getInstance;

  ///构造函数私有化，防止被误创建
  ImageUtil._internal();

  final Dio _dio = Dio();

  /// 网络图片转 Uint8List
  Future<Uint8List> networkImage2Uint8List(String imgUrl) async {
    try {
      var response = await _dio.get(imgUrl,
          options: Options(responseType: ResponseType.stream));
      final stream = await (response.data as ResponseBody).stream.toList();
      final result = BytesBuilder();
      for (Uint8List subList in stream) {
        result.add(subList);
      }
      return result.takeBytes();
    } on DioError catch (_) {
      rethrow;
    }
  }

  /// 图片加文字水印
  Future<String> imageTextWatermark(String text, String inImagePath) async {
    //返回Codec句柄
    ui.Codec codec =
        await ui.instantiateImageCodec(File(inImagePath).readAsBytesSync());
    //获取一帧图片FrameInfo
    ui.FrameInfo fi = await codec.getNextFrame();
    //获取ui.Image
    ui.Image image = fi.image;

    ui.PictureRecorder pictureRecorder = ui.PictureRecorder(); // 图片记录仪
    Canvas canvas = Canvas(pictureRecorder); //canvas接受一个图片记录仪

    Paint linePaint = Paint()
      ..color = Colors.white
      ..style = PaintingStyle.fill
      ..isAntiAlias = true //抗锯齿
      ..strokeCap = StrokeCap.round //线条末端的处理方式
      ..strokeWidth = 20.0;

    canvas.drawImage(image, const Offset(0, 0), linePaint); // 直接画图
    // "时间：2023-12-22 12:22:30\n位置：云南省昆明市五华区新明巷2001号靠近国家环境保护工业资源循环利用工程技术中心\n维度：25.078768\n经度：102.652595"
    TextPainter textPainter = TextPainter(
      text: TextSpan(
          text: text, style: TextStyle(color: Colors.white, fontSize: image.width/24)),
      textDirection: TextDirection.ltr,
      maxLines: 10,
    )..layout(maxWidth: image.width.toDouble());

    Paint textPaint = Paint()
      ..color = Colors.black38
      ..style = PaintingStyle.fill
      ..isAntiAlias = true //抗锯齿
      ..strokeCap = StrokeCap.round //线条末端的处理方式
      ..strokeWidth = 30.0;

    // 画黑色半透明底框
    canvas.drawRect(
        Rect.fromLTRB(0, image.height - textPainter.height,
            image.width.toDouble(), image.height.toDouble()),
        textPaint);

    // 画文字
    textPainter.paint(canvas, Offset(10, image.height - textPainter.height));

    final data = pictureRecorder.endRecording();
    ui.Image imageData = (await data.toImage(image.width, image.height));
    final byteData = await imageData.toByteData(format: ui.ImageByteFormat.png);
    Uint8List pngBytes = byteData!.buffer.asUint8List();
    String outImagePath = await FileUtil.uint8List2File(pngBytes);
    return outImagePath;
  }
}
